const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const GoodsService = require('../../services/good/goodsService');

class GoodController {
    static async getGoodsList(ctx) {
        // 确保请求体存在，如果不存在则初始化为空对象
        const requestData = ctx.request.body || {};
        
        // 解构分页参数，如果未提供则使用默认值
        const { pageNum = 1, pageSize = 10 } = requestData;
        
        // 创建查询数据对象，排除分页参数
        const queryData = { ...requestData };
        delete queryData.pageNum;
        delete queryData.pageSize;

        try {
            const res = await GoodsService.getGoodsList({ pageNum, pageSize }, queryData);
            response.success(ctx, { data: res });
        } catch (error) {
            response.error(ctx, { message: '获取商品列表失败: ' + error.message });
        }
    }
    static async getGoodsById(ctx) {
        const { id: goodsId } = ctx.request.body;
        const res = await GoodsService.getGoodsById(goodsId);
        res ? response.success(ctx, { data: res }) : response.error(ctx, { message: '商品不存在'});
    }
    static async createGoods(ctx) {
        const goodsData = ctx.request.body;
        await GoodsService.createGoods(goodsData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '商品名称重复'));
    }
    static async updateGoods(ctx) {
        const goodsData = ctx.request.body;
        await GoodsService.updateGoods(goodsData.id, goodsData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '商品名称重复'));
    }
    static async deleteGoods(ctx) {
        const { id } = ctx.request.body;
        
        try {
            const res = await GoodsService.deleteGoods(id);
            if (res) {
                response.success(ctx, { message: '删除成功' });
            } else {
                response.error(ctx, { message: '删除失败，未找到该商品' });
            }
        } catch (error) {
            response.error(ctx, { message: '删除商品失败: ' + error.message });
        }
    }
}
module.exports = GoodController;